<template>
  <div class="app-container">

    <u-page title="商品管理">

      <div slot="header">
        <el-button type="primary" icon="el-icon-edit" @click="hdlOpen(newForm)">
          {{ textMap['create'] }}
        </el-button>
      </div>

      <u-filtered>
        <el-form :inline="true" :model="listQuery" class="search-form">
          <el-form-item label="商品分类" prop="categoryId">
            <goods-category v-model="listQuery.categoryId" />
          </el-form-item>
          <el-form-item label="商品名称" prop="goodsName">
            <el-input v-model="listQuery.goodsName" placeholder="关键词搜索" clearable />
          </el-form-item>
          <el-form-item label="商品编号" prop="goodsNo">
            <el-input v-model="listQuery.goodsNo" placeholder="关键词搜索" clearable />
          </el-form-item>
          <el-form-item label="商品条码" prop="termNo">
            <el-input v-model="listQuery.termNo" placeholder="关键词搜索" clearable />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="listQuery.state" placeholder="请选择状态" class="state" clearable>
              <el-option value="" label="全部" />
              <el-option :value="1" label="上架" />
              <el-option :value="2" label="下架" />
            </el-select>
          </el-form-item>
          <el-form-item label="审核状态" prop="auditState">
            <el-select v-model="listQuery.auditState" placeholder="请选择状态" class="state" clearable>
              <el-option value="" label="全部" />
              <el-option :value="1" label="待审核" />
              <el-option :value="2" label="已审核" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="hdlFilter">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :disabled="!(selectData.length===1)" icon="el-icon-document-add" @click="copyGoods">复制商品</el-button>
          </el-form-item>
          <el-form-item>
            <el-dropdown>
              <el-button type="primary">
                批量操作<i class="el-icon-arrow-down el-icon--right" />
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :disabled="selectData.length===0" @click.native="hdlDel">批量删除</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-form-item>

        </el-form>
      </u-filtered>

      <u-table
        index="index"
        :data="list"
        :loading="listLoading"
        :options="listOptions"
        :columns="columns"
        :pagination.sync="listQuery"
        :fetch="hdlList"
        @selection-change="hdlSelectChange"
      >
        <template v-slot:right>
          <el-table-column label="操作" align="center" fixed="right">
            <template slot-scope="{ row }">
              <el-button v-show="row.auditState == 2||row.isAudit == 1" type="text" @click="handleEdit(row)">编辑</el-button>
              <el-button v-show="row.auditState == 1" type="text" @click="handlleAudit(row)">审核</el-button>
              <el-button type="text" @click="hdlDelete(row.id, row.goodsName)">删除</el-button>
              <el-dropdown>
                <el-button type="text">
                  更多<i class="el-icon-arrow-down el-icon--right" />
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item @click.native="copyLink(row)">复制商品链接</el-dropdown-item>
<!--                  <el-dropdown-item @click.native="downLoadQrCode(row)">下载商品二维码</el-dropdown-item>-->
                  <el-dropdown-item @click.native="downLoadQrCode2(row)">下载商品二维码</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </template>
      </u-table>

    </u-page>

    <u-dialog :title="textMap[dialogStatus]" :show.sync="dialogFormVisible" @confirm="dialogStatus==='create'?handleCreate():dialogStatus==='update'?handleUpdate():hdlAudit(true)">
      <el-form ref="dialogForm" :rules="rules" :disabled="dialogStatus==='audit'" :model="dataForm" label-width="120px">

        <el-tabs v-model="active">
          <el-tab-pane label="后端配置" name="first">

            <el-card shadow="never" class="panel">
              <el-form-item label="商品分类" prop="categoryId">
                <goods-category v-model="dataForm.categoryId" />
                <span style="margin-left: 10px">
                  <el-tooltip placement="top">
                    <div slot="content">
                      前端可根据筛选品类查到对应商品
                    </div>
                    <i class="el-icon-question" style="color:#909399;" />
                  </el-tooltip>
                </span>
              </el-form-item>
              <el-form-item label="商品名称" prop="goodsName">
                <el-input v-model="dataForm.goodsName" placeholder="请输入商品名称" style="width: 80%" />
                <span style="margin-left: 10px">
                  <el-tooltip placement="top">
                    <div slot="content">
                      前端商品名称
                    </div>
                    <i class="el-icon-question" style="color:#909399;" />
                  </el-tooltip>
                </span>
              </el-form-item>

              <!--        <el-form-item label="券商品编号" prop="goodsNo">-->
              <!--          <el-input v-model="dataForm.goodsNo" placeholder="请输入商品编号" />-->
              <!--        </el-form-item>-->
              <el-form-item label="商品条码" prop="termNo">
                <el-input v-model="dataForm.termNo" placeholder="请输入商品条码" style="width: 80%" />
                <span style="margin-left: 10px">
                  <el-tooltip placement="top">
                    <div slot="content">
                      商品条码，传入商友
                    </div>
                    <i class="el-icon-question" style="color:#909399;" />
                  </el-tooltip>
                </span>
              </el-form-item>

              <!--        <el-form-item label="卡券编号" prop="couponNo">-->
              <!--          <el-input type="=textarea" disabled="true" v-model="dataForm.couponNo" placeholder="请输入卡券商品编号" />-->
              <!--        </el-form-item>-->

              <el-form-item label="商品类型" prop="goodsType">
                <el-radio-group v-model="dataForm.goodsType">
                  <el-radio :label="1">定价商品</el-radio>
                  <el-radio :label="2">非定价商品</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="券商品类型" prop="couponGoodsType">
                <el-radio-group v-model="dataForm.couponGoodsType">
                  <el-radio :label="2">单次券</el-radio>
                  <el-radio :label="3">多次券</el-radio>
                  <el-radio :label="1">套券</el-radio>
                </el-radio-group>
                <span style="margin-left: 10px">
                  <el-tooltip placement="top">
                    <div slot="content">
                      发券、退款根据券商品类型判断
                    </div>
                    <i class="el-icon-question" style="color:#909399;" />
                  </el-tooltip>
                </span>
              </el-form-item>
              <el-form-item label="模板ID" prop="templateId">
                <el-input v-model="dataForm.templateId" placeholder="优惠券模板ID（注:通联卡劵模板ID）" oninput="value=value.replace(/[^\d]/g,'')" style="width: 80%" clearable>
                  <el-button slot="append" icon="el-icon-search" @click="handleTemplate(dataForm.templateId)" />
                </el-input>
              </el-form-item>
              <!--              <el-form-item label="优惠券名称">-->
              <!--                <el-input v-model="dataForm.couponName" placeholder="请输入优惠券名称" style="width: 80%" clearable maxlength="20" show-word-limit />-->
              <!--              </el-form-item>-->
              <!--              <el-form-item label="发放数量" prop="grantNum">-->
              <!--                <el-input-number v-model="dataForm.grantNum" :step="1" :min="0" />-->
              <!--                <el-button type="primary" style="margin-left: 10px" size="mini" @click="handleAddCoupon()">添加</el-button>-->
              <!--                <span style="margin-left: 10px">-->
              <!--                  <el-tooltip placement="top">-->
              <!--                    <div slot="content">-->
              <!--                      单次发放数量-->
              <!--                    </div>-->
              <!--                    <i class="el-icon-question" style="color:#909399;" />-->
              <!--                  </el-tooltip>-->
              <!--                </span>-->
              <!--              </el-form-item>-->

              <el-form-item label="卡券列表" prop="couponList">
                <el-table :data="dataForm.couponList" border style="width: 80%">
                  <el-table-column prop="templateId" label="卡券编号" />
                  <el-table-column prop="couponName" label="卡券名称" />
                  <el-table-column prop="grantNum" label="发放数量">
                    <template slot-scope="scope">
                      <el-input-number
                        v-model="scope.row.grantNum"
                        :min="1"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" align="center" fixed="right">
                    <template slot-scope="{ row }">
                      <el-button type="text" @click="hdlDeleteCoupon(row)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-form-item>
              <el-form-item label="划线价(元)" prop="originalPrice">
                <el-input v-model="dataForm.originalPrice" placeholder="请输入原价" style="width: 80%" />
                <span style="margin-left: 10px">
                  <el-tooltip placement="top">
                    <div slot="content">
                      商品价值
                    </div>
                    <i class="el-icon-question" style="color:#909399;" />
                  </el-tooltip>
                </span>
              </el-form-item>
              <el-form-item label="购买价格" prop="priceAmount">
                <el-col :span="7">
                  <el-input-number
                    v-model="dataForm.priceAmount"
                    :precision="2"
                    :step="0.01"
                    :min="0.0"
                    placeholder="请输入价格(元)"
                    size="medium"
                    oninput="value=value.replace(/[^\d.]/g,'')"
                  />
                </el-col>
                <el-col class="line" :span="1" style="margin-left: 20px;margin-right: 10px;">
                  <el-span style="width: 50px">积分</el-span>
                </el-col>
                <el-col :span="7">
                  <el-input-number v-model="dataForm.pricePoints" :step="1" :min="0" />
                  <span style="margin-left: 10px">
                    <el-tooltip placement="top">
                      <div slot="content">
                        价格和积分同时为0则为免费商品
                      </div>
                      <i class="el-icon-question" style="color:#909399;" />
                    </el-tooltip>
                  </span>
                </el-col>
              </el-form-item>
              <el-form-item label="商品库存" prop="inventory">
                <el-input-number v-model="dataForm.inventory" :step="1" :min="0" />
                <span style="margin-left: 10px">
                  <el-tooltip placement="top">
                    <div slot="content">
                      商品售卖总数量
                      库存为0则商品不限量
                    </div>
                    <i class="el-icon-question" style="color:#909399;" />
                  </el-tooltip>
                </span>
              </el-form-item>
              <!--        <el-form-item label="状态" prop="state">
                <el-radio-group v-model="dataForm.state">
                  <el-radio :label="1">上架</el-radio>
                  <el-radio :label="2">下架</el-radio>
                </el-radio-group>
              </el-form-item>-->
              <el-form-item label="上架日期" prop="onlineDate">
                <u-date-time-picker v-model="dataForm.onlineDate" value-format="yyyy-MM-dd HH:mm:ss" style="width: 80%" />
                <span style="margin-left: 10px">
                  <el-tooltip placement="top">
                    <div slot="content">
                      控制商品上、下架时间
                    </div>
                    <i class="el-icon-question" style="color:#909399;" />
                  </el-tooltip>
                </span>
              </el-form-item>
              <!--        <el-form-item label="使用日期" prop="useDate">
                <u-date-time-picker v-model="dataForm.useDate" value-format="yyyy-MM-dd HH:mm:ss" style="width: 50%" />
              </el-form-item>-->
              <!--        <el-form-item label="售卖日期" prop="sellDate">-->
              <!--          <u-date-time-picker v-model="dataForm.sellDate" value-format="yyyy-MM-dd HH:mm:ss" style="width: 50%" />-->
              <!--        </el-form-item>-->
              <el-form-item label="使用日期" prop="useDate">
                <u-date-time-picker v-model="dataForm.useDate" value-format="yyyy-MM-dd HH:mm:ss" style="width: 80%" />
                <span style="margin-left: 10px">
                  <el-tooltip placement="top">
                    <div slot="content">
                      控制商品使用退款时间
                    </div>
                    <i class="el-icon-question" style="color:#909399;" />
                  </el-tooltip>
                </span>
              </el-form-item>
              <el-form-item label="售卖时间段" prop="timeRangeList">
                <div v-for="(one,index) in dataForm.timeRangeList" :key="index" style="margin-top: 4px;">
                  <u-date-time-picker v-model="dataForm.timeRangeList[index]" value-format="yyyy-MM-dd HH:mm:ss" style="width: 80%" />
                  <el-button style="font-weight: bold;margin-left: 10px;" icon="el-icon-close" circle size="mini" @click="removeRange(index)" />
                  <span style="margin-left: 10px">
                    <el-tooltip placement="top">
                      <div slot="content">
                        控制商品售卖时间，可设置多个时间段
                      </div>
                      <i class="el-icon-question" style="color:#909399;" />
                    </el-tooltip>
                  </span>
                </div>
              </el-form-item>
              <el-button style="font-weight: bold;margin-left: 82.9%;" icon="el-icon-plus" circle size="mini" @click="addOneRange" />

              <!--        <el-form-item label="批次号" prop="batchNo">-->
              <!--          <el-input v-model="dataForm.batchNo" placeholder="请输入批次号" />-->
              <!--        </el-form-item>-->

              <!--        <el-form-item label="商品描述" prop="goodsDesc">-->
              <!--          <el-input v-model="dataForm.goodsDesc" type="textarea" placeholder="请输入商品描述" />-->
              <!--        </el-form-item>-->

              <el-form-item label="是否限购" prop="isLimit">
                <el-radio-group v-model="dataForm.isLimit">
                  <el-radio :label="1">不限购</el-radio>
                  <el-radio :label="2">每人限购总数</el-radio>
                  <el-radio :label="3">每人每天限购</el-radio>
                </el-radio-group>
                <span style="margin-left: 10px">
                  <el-tooltip placement="top">
                    <div slot="content">
                      控制商品购买数量
                    </div>
                    <i class="el-icon-question" style="color:#909399;" />
                  </el-tooltip>
                </span>
              </el-form-item>
              <el-form-item v-show="dataForm.isLimit === 2" label="每人限购总数" prop="quota">
                <el-input-number v-model="dataForm.quota" :step="1" :min="0" />
              </el-form-item>
              <el-form-item v-show="dataForm.isLimit === 3" label="每人每天限购" prop="total">
                <el-input-number v-model="dataForm.total" :step="1" :min="0" />
              </el-form-item>

              <el-form-item label="退款方式" prop="isRefund">
                <el-radio-group v-model="dataForm.isRefund">
                  <el-radio :label="1">到期自动退款</el-radio>
                  <el-radio :label="2">不退款</el-radio>

                </el-radio-group>
                <span style="margin-left: 10px">
                  <el-tooltip placement="top">
                    <div slot="content">
                      控制商品是否可以退款
                    </div>
                    <i class="el-icon-question" style="color:#909399;" />
                  </el-tooltip>
                </span>
              </el-form-item>

              <el-form-item label="指定用户" prop="isSpecifyUser">
                <el-radio-group v-model="dataForm.isSpecifyUser">
                  <el-radio :label="1">启用</el-radio>
                  <el-radio :label="2">不启用</el-radio>
                </el-radio-group>
                <span style="margin-left: 10px">
                  <el-tooltip placement="top">
                    <div slot="content">
                      指定用户购买
                    </div>
                    <i class="el-icon-question" style="color:#909399;" />
                  </el-tooltip>
                </span>
              </el-form-item>
              <!--        <el-form-item label="发放方式" prop="grantType">
                <el-radio-group v-model="dataForm.grantType">
                  <el-radio :label="1">后台发放</el-radio>
                  <el-radio :label="2">扫码领取</el-radio>
                  <el-radio :label="3">卡券超市</el-radio>
                  <el-radio :label="4">积分商城兑礼</el-radio>
                </el-radio-group>
              </el-form-item>-->

              <el-form-item v-show="dataForm.isSpecifyUser === 1" label="" prop="users">
                <el-input v-model="dataForm.users" type="textarea" :autosize="{ minRows: 2}" placeholder="请输入手机号用英文逗号分割" />
              </el-form-item>

              <el-form-item label="活动对象" prop="cardTypeList">
                <div style="display: flex;">
                  <el-checkbox-group v-model="dataForm.cardTypeList" :min="1">
                    <el-checkbox label="104">微会员</el-checkbox>
                    <el-checkbox label="101">金卡</el-checkbox>
                    <el-checkbox label="102">红宝石卡</el-checkbox>
                    <el-checkbox label="103">钻石卡</el-checkbox>

                  </el-checkbox-group>
                  <span style="margin-left: 10px">
                    <el-tooltip placement="top">
                      <div slot="content">
                        指定会员等级购买
                      </div>
                      <i class="el-icon-question" style="color:#909399;" />
                    </el-tooltip>
                  </span>
                </div>

              </el-form-item>

              <!--              <el-form-item label="黑名单" prop="blackList">
                <el-input v-model="dataForm.blackList" type="textarea" :autosize="{ minRows: 2}" placeholder="请输入openid用逗号分割" style="width: 80%;" />
                <span style="margin-left: 10px">
                  <el-tooltip placement="top">
                    <div slot="content">
                      指定那些用户不能买
                    </div>
                    <i class="el-icon-question" style="color:#909399;" />
                  </el-tooltip>
                </span>
              </el-form-item>-->

              <el-form-item label="黑名单" prop="blackList">
                <blacklist v-model="dataForm.blackList" style="width: 80%" />
                <span style="margin-left: 10px">
                  <el-tooltip placement="top">
                    <div slot="content">
                      指定那些用户不能买
                    </div>
                    <i class="el-icon-question" style="color:#909399;" />
                  </el-tooltip>
                </span>
                <el-input v-model="dataForm.blackContent" type="textarea" placeholder="批量操作名单,手机号" clearable rows="10" style="margin-top: 10px;width: 80%;" />

                <u-tip-info title="格式: 手机号+换行或者英文逗号" />

              </el-form-item>
            </el-card>

          </el-tab-pane>
          <el-tab-pane label="用户端显示" name="second">

            <el-form-item prop="goodsLogo" label="商品logo图片">
              <div style="display: flex">
                <u-upload v-model="dataForm.goodsLogo" :value="dataForm.goodsLogo" name="file" tips="建议尺寸:650 * 350像素" />
                <span style="margin-left: 10px">
                  <el-tooltip placement="top">
                    <div slot="content">
                      前端商品列表图片展示
                    </div>
                    <i class="el-icon-question" style="color:#909399;" />
                  </el-tooltip>
                </span>
              </div>

            </el-form-item>
            <el-form-item label="商品轮播图片" prop="goodsPollingImage">
              <div style="display: flex">
                <u-upload v-model="dataForm.goodsPollingImage" :value="dataForm.goodsPollingImage" name="file" :multiple="true" tips="建议尺寸:650 * 350像素;内容主体所在区域,推荐尺寸650 * 350像素" />
                <span style="margin-left: 10px">
                  <el-tooltip placement="top">
                    <div slot="content">
                      前端商品详情页图片展示
                    </div>
                    <i class="el-icon-question" style="color:#909399;" />
                  </el-tooltip>
                </span>
              </div>

            </el-form-item>
            <el-form-item label="权益须知" prop="equity">
              <u-tinymce v-model="dataForm.equity" :height="300" />
              <!--              <el-input v-model="dataForm.equity" type="textarea" :autosize="{ minRows: 2}" placeholder="请输入内容" style="width: 80%" />-->
              <span style="margin-left: 10px">
                <el-tooltip placement="top">
                  <div slot="content">
                    使用说明
                  </div>
                  <i class="el-icon-question" style="color:#909399;" />
                </el-tooltip>
              </span>
            </el-form-item>
            <el-form-item label="权重" prop="sort">
              <el-input-number v-model="dataForm.sort" :step="1" :min="0" />
              <span style="margin-left: 10px">
                <el-tooltip placement="top">
                  <div slot="content">
                    类目排序，控制商品前端展示顺序，由大到小
                  </div>
                  <i class="el-icon-question" style="color:#909399;" />
                </el-tooltip>
              </span>
            </el-form-item>

          </el-tab-pane>
        </el-tabs>

      </el-form>
      <div v-show="dialogStatus==='audit'">
        <el-divider />
      </div>
      <el-form :model="dataForm" label-width="125px">
        <el-form-item v-show="dialogStatus==='audit'" label="变更内容" prop="record">
          <el-input v-model="dataForm.record" type="textarea" autosize :disabled="true" />
        </el-form-item>
        <el-form-item v-show="dialogStatus==='audit'" label="审核意见" prop="isPass">
          <el-radio-group v-model="dataForm.isPass">
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="2">不通过</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </u-dialog>
    <el-drawer title="绑定卡券" :visible.sync="bindDialogVisible" direction="rtl" size="50%">
      <el-button type="primary" icon="el-icon-edit" style="margin-bottom: 10px; " @click="addCoupon(form)">添加</el-button>
      <el-table :data="couponList" border style="width: 100%">
        <el-table-column prop="couponId" label="卡券编号" />
        <el-table-column prop="couponName" label="卡券名称" />
        <el-table-column prop="grantNum" label="发放数量" />
        <el-table-column label="操作" align="center" fixed="right">
          <template slot-scope="{ row }">
            <el-button type="text" @click="hdlUnbind(row,2)">解绑</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-drawer>

    <u-dialog title="添加卡券" :show.sync="addCouponDialogVisible" @confirm="hdlBindSubmit()">
      <el-form :model="dataForm2" label-width="80px">
        <el-form-item label="卡券" prop="couponId">
          <cpls v-model="dataForm2.couponId" width="160px" />
        </el-form-item>
        <el-form-item label="发放数量" prop="grantNum">
          <el-input-number v-model="dataForm2.grantNum" :step="1" :min="0" />
        </el-form-item>
      </el-form>
    </u-dialog>

    <u-dialog title="修改库存" :show.sync="inventoryDialogVisible" width="600px" @confirm="hdlInventory()">
      <el-form :model="dataForm3" label-width="80px">
        <el-form-item label="库存" prop="inventory">
          <el-input-number v-model="dataForm3.inventory" :step="1" :min="0" />
        </el-form-item>
      </el-form>
    </u-dialog>

    <u-dialog title="商品审核" :show.sync="auditDialogVisible" width="600px" @confirm="hdlAudit(false)">
      <el-form :model="dataForm4" label-width="80px">
        <el-form-item label="变更内容" prop="record">
          <el-input v-model="dataForm4.record" type="textarea" autosize :disabled="true" />
        </el-form-item>
        <el-form-item label="审核意见" prop="isPass">
          <el-radio-group v-model="dataForm4.isPass">
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="2">不通过</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </u-dialog>

  </div>
</template>
<script>
import GoodsCategory from '../components/GoodsCategory'
import cpls from '../components/cpls'
import { saveAs } from 'file-saver'
import axios from 'axios'
import blacklist from '@/components/module/blacklist.vue'
export default {
  components: {
    blacklist,
    GoodsCategory,
    cpls
  },
  data() {
    return {
      api: this.$u.api.PluginsCouponmallGoods,
      // 表格
      columns: [
        {
          prop: 'category',
          label: '商品分类',
          render: (h, params) => {
            const { category } = params.row
            if (category) {
              return h('div', category.name)
            }
          }
        },
        {
          prop: 'couponGoodsType',
          label: '卡券类型',
          render: (h, params) => {
            const { couponGoodsType } = params.row
            if (couponGoodsType === 1) {
              return h('el-tag', { props: { type: 'info' }}, '套券')
            } else if (couponGoodsType === 2) {
              return h('el-tag', { props: { type: 'info' }}, '单次券')
            } else if (couponGoodsType === 3) {
              return h('el-tag', { props: { type: 'info' }}, '多次券')
            }
          }
        },
        {
          prop: 'goodsNo',
          label: '商品编号',
          width: '100'
        },
        /* {
          prop: 'termNo',
          label: '商品条码',
          width: '100'
        }, */
        {
          prop: 'goodsLogo',
          label: '商品LOGO',
          image: true
        },
        {
          prop: 'goodsName',
          label: '商品名称',
          width: '100'
        },
        {
          prop: 'originalPrice',
          label: '商品原价',
          render: (h, params) => {
            const { originalPrice } = params.row
            if (originalPrice) {
              return h('div', originalPrice + '元')
            }
          }
        },
        {
          prop: 'price',
          label: '购买价格',
          width: '100'
        },
        // {
        //   prop: 'price',
        //   label: '购买价格',
        //   width: '100',
        //   render: (h, params) => {
        //     const { priceAmount, pricePoints } = params.row
        //     let price = '';
        //     if(priceAmount){
        //       price += priceAmount + "元";
        //     }else{
        //       price += 0 + "元";
        //     }
        //     if (price.length > 1) {
        //       price += "+";
        //     }
        //     if (pricePoints) {
        //       price += pricePoints + "积分";
        //     }else{
        //       price += 0 + "积分";
        //     }
        //     return h('div', price)
        //   }
        // },
        {
          prop: 'haveSoldNum',
          label: '已售卖数量'
        },
        {
          prop: 'inventory',
          label: '总库存',
          width: '80',
          render: (h, params) => {
            const { inventory } = params.row
            return [
              inventory, ' ',
              h('el-button', { props: { icon: 'el-icon-edit', size: 'mini', circle: true }, on: {
                click: () => this.changeInventory(params.row)
              }})
            ]
          }
        },
        {
          prop: 'state',
          label: '展示状态',
          width: '90',
          render: (h, params) => {
            const { state } = params.row
            if (state === 2) {
              return [h('el-tag', { props: { type: 'danger' }}, '下架'),
                h('el-button', { props: { icon: 'el-icon-top', size: 'mini', circle: true }, on: {
                  click: () => this.upDownGoods(params.row)
                }})]
            } else if (state === 1) {
              return [h('el-tag', { props: { type: 'success' }}, '上架'),
                h('el-button', { props: { icon: 'el-icon-bottom', size: 'mini', circle: true }, on: {
                  click: () => this.upDownGoods(params.row)
                }})
              ]
            }
          }
        },
        {
          prop: 'auditState',
          label: '审核状态',
          render: (h, params) => {
            const { auditState } = params.row
            if (auditState === 1) {
              return h('el-tag', { props: { type: 'danger' }}, '待审核')
            } else if (auditState === 2) {
              return h('el-tag', { props: { type: 'success' }}, '已审核')
            }
          }
        },
        // {
        //   prop: 'validityDate',
        //   label: '售卖日期',
        //   width: '180',
        //   render: (h, params) => {
        //     let { sellStartTime, sellEndTime } = params.row
        //     if (!sellStartTime) {
        //       sellStartTime = '不限制'
        //     }
        //     if (!sellEndTime) {
        //       sellEndTime = '不限制'
        //     }
        //     return [
        //       h('el-tag', { props: { effect: 'plain' }}, '起始:' + sellStartTime),
        //       h('br'),
        //       h('el-tag', { props: { effect: 'plain' }}, '终止:' + sellEndTime)
        //     ]
        //   }
        // },
        /* {
          prop: 'useDate',
          label: '使用日期',
          width: '180',
          render: (h, params) => {
            let { useStartTime, useEndTime } = params.row
            if (!useStartTime) {
              useStartTime = '不限制'
            }
            if (!useEndTime) {
              useEndTime = '不限制'
            }
            return [
              h('el-tag', { props: { effect: 'plain' }}, '起始:' + useStartTime),
              h('br'),
              h('el-tag', { props: { effect: 'plain' }}, '终止:' + useEndTime)
            ]
          }
        }, */
        {
          prop: 'onlineDate',
          label: '上架日期',
          width: '180',
          render: (h, params) => {
            let { onlineStartTime, onlineEndTime } = params.row
            if (!onlineStartTime) {
              onlineStartTime = '不限制'
            }
            if (!onlineEndTime) {
              onlineEndTime = '不限制'
            }
            return [
              h('el-tag', { props: { effect: 'plain' }}, '起始:' + onlineStartTime),
              h('br'),
              h('el-tag', { props: { effect: 'plain' }}, '终止:' + onlineEndTime)
            ]
          }
        },
        {
          prop: 'timeRangeList',
          label: '售卖时间段',
          width: '180',
          render: (h, params) => {
            let { sellStartTime, sellEndTime, timeRangeList } = params.row
            if (!sellStartTime) {
              sellStartTime = '不限制'
            }
            if (!sellEndTime) {
              sellEndTime = '不限制'
            }
            const res = []
            const br = h('br')
            for (let i = 0; i < timeRangeList.length; i++) {
              const start = h('el-tag', { props: { effect: 'plain' }}, '起始:' + timeRangeList[i][0])
              const end = h('el-tag', { props: { effect: 'plain' }}, '终止:' + timeRangeList[i][1])
              res.push(start)
              res.push(br)
              res.push(end)
              if (i !== timeRangeList.length - 1) { res.push(br) }
            }
            return res
          }
        },
        {
          prop: 'createdBy',
          label: '创建人'
        },
        {
          prop: 'auditPerson',
          label: '审核人'
        },
        {
          prop: 'createdAt',
          label: '创建时间',
          timestamp: true
        }
      ],

      list: [],
      listLoading: false,
      listOptions: {
        index: true,
        mutiSelect: true, // boolean 是否多选
        stripe: true // boolean 斑马纹

      },
      listQuery: {
        pageNumber: 1,
        pageSize: 10,
        totalCount: 1,
        beginTime: '',
        endTime: '',
        name: '',
        mobile: '',
        status: ''
      },

      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑商品',
        create: '新增商品',
        audit: '审核新增商品'
      },
      dataForm: {
        inventory: 0,
        quota: 0,
        pricePoints: 0,
        timeRangeList: [[new Date().toISOString().slice(0, 10) + ' 00:00:00', new Date().toISOString().slice(0, 10) + ' 23:59:59']]
      },
      newForm: {
        goodsPollingImage: 'https://csms.chiconysquare.net/assets/coupon/logo.png',
        goodsLogo: 'https://csms.chiconysquare.net/assets/coupon/logo.png',
        termNo: '134521',
        goodsType: 2,

        isSpecifyUser: 2,
        cardTypeList: ['104', '101', '102', '103'],
        isRefund: 1,
        couponGoodsType: 2,
        state: 1,
        isLimit: 1,
        grantType: 3,
        timeRangeList: [[new Date().toISOString().slice(0, 10) + ' 00:00:00', new Date().toISOString().slice(0, 10) + ' 23:59:59']],
        couponList: [],
        couponName: '',
        quota: 0,
        total: 0,
        priceAmount: 0.0,
        pricePoints: 0
      },
      dataSource: [['2000-01-01 00:00:00', '2000-01-01 00:00:00']],
      dataForm2: {},
      dataForm3: {},
      dataForm4: {},
      bindDialogVisible: false,
      inventoryDialogVisible: false,
      auditDialogVisible: false,
      addCouponDialogVisible: false,
      couponList: [],
      couponGoodsId: 0,
      inventoryVisible: false,
      cardTypeList: [
        {
          value: '104',
          label: '微会员'
        }, {
          value: '101',
          label: '金卡'
        }, {
          value: '102',
          label: '红宝石卡'
        }, {
          value: '103',
          label: '钻石卡'
        }
      ],
      rules: {
        goodsType: [
          { required: true, message: '商品类型不能为空', trigger: 'blur' }
        ],
        categoryId: [
          { required: true, message: '商品类目不能为空', trigger: 'blur' }
        ],
        termNo: [
          { required: true, message: '商品条码不能为空', trigger: 'blur' }
        ],
        goodsLogo: [
          { required: true, message: '商品LOGO不能为空', trigger: 'blur' }
        ],
        goodsName: [
          { required: true, message: '商品名称不能为空', trigger: 'blur' }
        ],
        // goodsDesc: [
        //   {required: true, message: "商品描述不能为空", trigger: "blur"}
        // ],
        state: [
          { required: true, message: '商品状态不能为空', trigger: 'blur' }
        ],
        // scoreType: [
        //   {required: true, message: "积分项不能为空", trigger: "blur"}
        // ],
        failHandle: [
          { required: true, message: '发放卡券处理类型不能为空', trigger: 'blur' }
        ],
        couponNo: [
          { required: true, message: '卡券列表不能为空', trigger: 'blur' }
        ],
        // goodsPollingImage: [
        //   {required: true, message: "图片轮播图不能为空", trigger: "blur"}
        // ],
        cardTypeList: [
          { required: true, message: '活动对象必选', trigger: 'blur' }
        ],
        onlineDate: [
          { required: true, message: '上架时间不能为空', trigger: 'blur' }
        ],
        useDate: [
          { required: true, message: '使用时间不能为空', trigger: 'blur' }
        ],
        timeRangeList: [
          { required: true, message: '售卖时间段不能为空', trigger: 'blur' }
        ],
        inventory: [
          { required: true, message: '库存不能为空', trigger: 'blur' }
        ],
        equity: [
          { required: true, message: '权益不能为空', trigger: 'blur' }
        ]
        // sort: [
        //   { required: true, message: "权重不能为空", trigger: "blur" }
        // ],
      },
      // 删除选中数据
      selectData: [],
      active: 'first'
    }
  },
  watch: {
    // 监听 goodsLogo 的变化
    'dataForm.goodsLogo'(newVal) {
      // 当 goodsLogo 变化时，同步更新 goodsPollingImage
      this.dataForm.goodsPollingImage = newVal
    }
  },
  created() {
    this.hdlList()
  },
  methods: {
    // 打开修改弹窗
    handleEdit(row) {
      const { sellStartTime, sellEndTime, useStartTime, useEndTime, onlineStartTime, onlineEndTime, cardType, couponNo } = row
      // row.sellDate = []
      row.useDate = []
      if (useStartTime && useEndTime) {
        row.useDate = [useStartTime, useEndTime]
      }
      if (onlineStartTime && onlineEndTime) {
        row.onlineDate = [onlineStartTime, onlineEndTime]
      }
      if (cardType) {
        row.cardTypeList = cardType.split(',')
      }
      if (couponNo) {
        row.couponList = JSON.parse(couponNo)
      }
      row.couponName = ''
      row.templateId = ''
      this.hdlEdit(row)
    },
    // 新增事件
    handleCreate() {
      const { sellDate, useDate, timeRangeList, cardTypeList, couponList, onlineDate } = this.dataForm
      // if (sellDate) {
      //   this.dataForm.sellStartTime = sellDate[0]
      //   this.dataForm.sellEndTime = sellDate[1]
      // }
      if (useDate) {
        this.dataForm.useStartTime = useDate[0]
        this.dataForm.useEndTime = useDate[1]
      }
      if (onlineDate) {
        this.dataForm.onlineStartTime = onlineDate[0]
        this.dataForm.onlineEndTime = onlineDate[1]
      }
      if (timeRangeList) {
        this.dataForm.timeJson = JSON.stringify(timeRangeList)
      }
      if (cardTypeList) {
        this.dataForm.cardType = cardTypeList.toString()
      }
      if (couponList) {
        this.dataForm.couponNo = JSON.stringify(couponList)
      }
      this.hdlCreate()
    },
    // 打开修改弹窗
    handleUpdate() {
      const { sellDate, useDate, timeRangeList, couponList, onlineDate } = this.dataForm
      if (useDate) {
        this.dataForm.useStartTime = useDate[0]
        this.dataForm.useEndTime = useDate[1]
      }
      if (onlineDate) {
        this.dataForm.onlineStartTime = onlineDate[0]
        this.dataForm.onlineEndTime = onlineDate[1]
      }
      if (timeRangeList) {
        this.dataForm.timeJson = JSON.stringify(timeRangeList)
      }
      if (couponList) {
        this.dataForm.couponNo = JSON.stringify(couponList)
      }
      this.dataForm.cardType = this.dataForm.cardTypeList.toString()
      this.hdlUpdate()
    },
    // 绑定卡券事件
    hdlBind(row) {
      const self = this
      self.bindDialogVisible = true
      self.couponGoodsId = row.id
      self.api.fetch(row.id).then(res => {
        const json = res.data.couponNo
        self.couponList = JSON.parse(json)
      })
    },
    hdlUnbind(row, operType) {
      const self = this
      if (operType) {
        row.operType = operType
        row.goodsNo = self.couponGoodsId
      }
      self.$confirm('确定要解绑' + row.couponName + '吗？', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => {
        self.api.couponBind(row).then(res => {
          self.$u.msg('解绑成功')
          self.api.fetch(self.couponGoodsId).then(res => {
            const json = res.data.couponNo
            self.couponList = JSON.parse(json)
          })
        })
      }).catch(() => {
      })
    },
    hdlBindSubmit() {
      const self = this
      self.dataForm2.operType = 1
      self.dataForm2.goodsNo = self.couponGoodsId
      self.api.couponBind(self.dataForm2).then(res => {
        self.addCouponDialogVisible = false
        // 通知信息
        self.$u.msg('绑定成功')
        self.api.fetch(self.couponGoodsId).then(res => {
          const json = res.data.couponNo
          self.couponList = JSON.parse(json)
        })
      })
    },
    addCoupon(row) {
      const self = this
      // 初始化数据源
      self.dataForm2 = Object.assign({}, row)
      // 打开弹框状态
      self.addCouponDialogVisible = true
    },
    changeInventory(row) {
      this.inventoryDialogVisible = true
      this.dataForm3 = row
      console.log(row)
    },
    addOneRange() {
      const date = new Date().toISOString().slice(0, 10)
      const temp = [date + ' 00:00:00', date + ' 23:59:59']
      console.log(this.dataForm.timeRangeList)
      console.log(this.newForm.timeRangeList)
      this.dataForm.timeRangeList.push(temp)
      this.dataSource.push(temp)
    },
    removeRange(index) {
      if (this.dataForm.timeRangeList.length === 1) {
        this.$message.warning('至少保留一个时间段')
        return
      }
      this.dataForm.timeRangeList.splice(index, 1)
    },
    hdlInventory() {
      const self = this
      self.api.update(this.dataForm3).then(() => {
        // 刷新数据列表
        self.hdlList()
        // 关闭弹窗状态
        self.inventoryDialogVisible = false
        // 通知信息
        self.$u.msg('更新成功')
      })
    },
    handlleAudit(row) {
      const self = this
      if (row.isAudit) {
        const { sellStartTime, sellEndTime, useStartTime, useEndTime, onlineStartTime, onlineEndTime, cardType, couponNo } = row
        // row.sellDate = []
        row.useDate = []
        if (useStartTime && useEndTime) {
          row.useDate = [useStartTime, useEndTime]
        }
        if (onlineStartTime && onlineEndTime) {
          row.onlineDate = [onlineStartTime, onlineEndTime]
        }
        if (cardType) {
          row.cardTypeList = cardType.split(',')
        }
        if (couponNo) {
          row.couponList = JSON.parse(couponNo)
        }
        row.couponName = ''
        row.templateId = ''
        // 初始化数据源
        self.dataForm = Object.assign({}, row)
        // self.dataForm4 = Object.assign({}, row)
        self.dataForm.isPass = 1
        // 打开编辑状态
        self.dialogStatus = 'audit'
        // 打开弹框状态
        self.dialogFormVisible = true
        // 清除表单验证状态
        self.$nextTick(() => {
          self.$refs['dialogForm'].clearValidate()
        })
      } else {
        self.dataForm4 = row
        self.dataForm4.isPass = 1
        self.auditDialogVisible = true
      }
    },
    hdlAudit(isAdd) {
      const self = this
      let data = {}
      if (isAdd) {
        data = this.dataForm
      } else {
        data = this.dataForm4
      }
      data = this.dataForm
      self.dataForm4.auditState = self.dataForm4.isPass
      self.api.auditGoods(data).then(() => {
        // 刷新数据列表
        self.hdlList()
        // 关闭弹窗状态
        self.auditDialogVisible = false
        self.dialogFormVisible = false
        // 通知信息
        self.$u.msg('审核成功')
      })
    },
    // 模板数据补充
    handleTemplate(templateId) {
      const self = this
      self.api.template({ templateId }).then(res => {
        const { couponName } = res.data
        self.dataForm.couponName = couponName
        self.dataForm.grantNum = 1

        if (self.dataForm.couponGoodsType !== 1) {
          self.dataForm.useStartTime = res.data.validityBeginDate
          self.dataForm.useEndTime = res.data.validityEndDate
          self.dataForm.useDate = [self.dataForm.useStartTime, self.dataForm.useEndTime]
        }

        self.handleAddCoupon()
      })
    },
    handleAddCoupon() {
      const self = this
      const id = self.dataForm.templateId
      const name = self.dataForm.couponName
      const num = self.dataForm.grantNum
      if (!id) { self.$message.warning('模板ID不能为空'); return }
      if (!name) { self.$message.warning('卡券名称不能为空'); return }
      if (!num) { self.$message.warning('发放数量不能为空'); return }
      const temp = { templateId: id, couponName: name, grantNum: num }
      let flag = true
      if (self.dataForm.couponList !== undefined) {
        self.dataForm.couponList.forEach((item) => {
          if (id == item.couponId) {
            self.$message.warning('请勿重复绑定卡券！')
            flag = false
          }
        })
        if (flag) {
          self.dataForm.couponList.push(temp)
        }
      }
    },
    hdlDeleteCoupon(row) {
      const self = this
      const res = self.dataForm.couponList
      for (let i = 0; i < res.length; i++) {
        if (res[i].templateId == row.templateId) {
          console.log(row.templateId)
          self.dataForm.couponList.splice(i, 1)
        }
      }
    },
    upDownGoods(row) {
      const self = this
      const data = row
      const action = row.state == 1 ? '下架' : '上架'
      self.$confirm('是否' + action + row.goodsName, '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => {
        // 处理确认事件
        data.state = action == '上架' ? 1 : 2
        self.api.update(data).then(() => {
          // 刷新数据列表
          self.hdlList()
          // 通知信息
          self.$u.msg(action + '成功')
        })
      }).catch(() => {
      })
    },
    copyGoods() {
      const self = this
      // 检查选中数据源
      if (self.selectData.length === 0) {
        self.$u.toast('请选择要复制的商品', 'error')
        return false
      }
      console.log(self.selectData)
      const goods = self.selectData[0]
      self.$confirm('是否复制商品： ' + goods.goodsName + '？', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => {
        // 处理确认事件
        self.api.create(goods).then(() => {
          // 刷新数据列表
          self.hdlList()
          // 通知信息
          self.$u.msg('复制商品成功')
        })
      }).catch(() => {
      })
    },
    copyLink(row) {
      console.log(row.goodsNo)
      const self = this
      self.api.getUrlLink(row.goodsNo).then(res => {
        const url = res.data
        if (navigator.clipboard) { // 检查是否支持Clipboard API
          navigator.clipboard.writeText(url)
            .then(() => { alert('复制成功！') })
            .catch(err => { console.error('复制失败', err) }) // 使用Fallback方法处理不支持Clipboard API的情况或捕获错误情况。
        } else { // 使用Fallback方法（例如document.execCommand）处理旧浏览器或不支持Clipboard API的情况。
          const el = document.createElement('textarea')
          el.value = url
          document.body.appendChild(el)
          el.select()
          document.execCommand('copy')
          document.body.removeChild(el)
        }
      })
    },
    downLoadQrCode(row) {
      const self = this
      const name = row.goodsName
      return axios({
        method: 'get',
        url: 'nt/plugins/couponmall/goods/getGoodsQrCode/' + row.goodsNo,
        responseType: 'blob'
      }).then(res => {
        const blobData = new Blob([res.data], { type: 'application/vnd.ms-excel;charset=utf-8' })
        saveAs(blobData, name + '.png')
      })
    },
    downLoadQrCode2(row) {
      const self = this
      const name = row.goodsName
      return axios({
        method: 'get',
        url: 'nt/plugins/couponmall/goods/getGoodsQrCode2/' + row.goodsNo,
        responseType: 'blob'
      }).then(res => {
        const blobData = new Blob([res.data], { type: 'application/vnd.ms-excel;charset=utf-8' })
        saveAs(blobData, name + '.png')
      })
    }
  }
}
</script>
<style lang="scss" scoped>
  .app-container{

    & >>> .el-drawer__body {
      overflow: auto;
    }

    .uploader{

      .thumb{
        display: inline-block;
        text-align: center;
        outline: none;
        background-color: #fbfdff;
        border: 1px dashed #c0ccda;
        border-radius: 6px;
        box-sizing: border-box;
        width: 120px;
        height: 120px;
        cursor: pointer;
        line-height: 120px;
        vertical-align: top;

        ::v-deep {
          .el-image {
            width: 100%;
            height: 100%;
            display: block;
            border-radius: 6px;
          }

          img{
            width: 100%;
            height: 100%;
            display: block;
            border-radius: 6px;
          }
        }
      }
    }

  }
</style>
